<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\base\BaseController;
use app\home\validate\EnterpriseCheck;
use app\home\validate\GoodsCheck;
use app\home\validate\ItemCheck;
use app\home\validate\EquipmentWorkHoursCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class EquipmentWorkHours extends BaseController
{
    /**
     * 固定资产工时管理
     */
    public function index()
    {
        $param = get_params();

        View::assign('date', date('Y'));
        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;
        if (request()->isAjax()) {

            $where = [];

            $where['eid']       = $eid;
            $where['status']    = 0;
            $where['year']      = !empty($param['year']) ? $param['year'] : date('Y');

            $work_user = Db::name('EquipmentWorkHours')->where($where)->group('month')->field('year,month,sum(work_hours) as all_time,eid')->select()->toArray();

            //复制自定义id
            foreach($work_user as $k => &$v){

                $v['id'] = $k+1;
            }


            $data['data'] = $work_user;
//        View::assign('work_user', $work_user);
            return table_assign(0, '', $data);
        }else{
            return view();
        }


    }

    /**
     * 添加/编辑固定资产工时
     */
    public function operation()
    {
        $param = get_params();
        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        if (request()->isAjax()) {
            try {
                validate(EquipmentWorkHoursCheck::class)->scene('add')->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }

            $year = date('Y' , strtotime($param['time']));
            $month = date('m' , strtotime($param['time']));

            $count = Db::name('EquipmentWorkHours')->where(['eid' => $eid ,'year' => $year , 'month' => $month])->count();

            if($count > 0){
                Db::name('EquipmentWorkHours')->where(['eid' => $eid ,'year' => $year , 'month' => $month])->delete();
            }

            $user_work_hours = $param['user_work_hours_value'];

            foreach($user_work_hours as $key => &$value){

                $value['eid']                   =  $eid;
                $value['time']                  = strtotime($param['time']);
                $value['create_time']           = time();
                $value['year']                  = $year;
                $value['month']                  = $month;
                $value['create_time']           = time();
                unset($value['user_work_hours']);

            }

            $insertId = Db::name('EquipmentWorkHours')->strict(false)->field(true)->insertAll($user_work_hours);

            if ($insertId) {
                add_log('add', '', $param);
            }
            return to_assign();
        }else {
            $enterprise = Db::name('Enterprise')->where(['id'=>$eid])->find();

            $name = $enterprise['title'] ?? '';

            View::assign('e_name' , $name);
            return view();
        }
    }


    /**
     * 获取固定资产表头信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getEquItem(){

        $param = get_params();
        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        $time = !empty($param['time']) ? $param['time'] : date('Y-m');

        $year       = date('Y' , strtotime($time));
        $month      = date('m' , strtotime($time));

        //查询当前月份是否存在已添加的数据
        $count = Db::name('EquipmentWorkHours')->where(['eid' => $eid,'year'=>$year , 'month' => $month , 'status' => 0])->count();
        $detail = [];
        if($count > 0){
            $where = [
                'ewh.eid' => $eid,
                'ewh.year' => $year,
                'ewh.month' => $month,
                'ewh.status' => 0,
            ];
            //获取固定资产
            $user = Db::name('EquipmentWorkHours')->alias('ewh')
                ->where($where)
                ->group('ewh.eq_id')
                ->field('ewh.eq_id as id,e.name,ewh.all_hours')
                ->join('Equipment e' , 'e.id = ewh.eq_id')
                ->select()->toArray();

            //获取项目
            $item = Db::name('EquipmentWorkHours')->alias('ewh')
                ->where($where)
                ->group('ewh.item_id')
                ->field('ewh.item_id as id,i.name')
                ->join('Item i' , 'i.id = ewh.item_id')
                ->select()->toArray();

            $detail = $this->_getHours($eid , $year , $month);
        }else{
            //查询固定资产
            $user = Db::name('Equipment')
                ->field('name,id,0 as all_hours')
                ->where(['eid'=> $eid , 'status'=>0])
                ->order('create_time asc')->select()->toArray();

            $month_time = Db::name('MonthTime')
                ->field('work_hours')
                ->where(['year'=>$year , 'month' => $month , 'eid'=>$eid])
                ->find();

            if(!empty($month_time)){
                foreach($user as $k => &$v){
                    $v['all_hours'] = $month_time['work_hours'];
                }
            }

            //查询项目
            $item = Db::name('Item')->field('id,name')->where('eid','=',$eid)->where('status', '>=', 0)->order('create_time asc')->select();
        }

        foreach($user as $k => &$v){
            $info = $item;
            foreach($info as $kk => &$vv){

                $vv['work_hours'] = !empty($detail) ? $detail["{$v['id']}-{$vv['id']}"]['work_hours'] ?? 0 : 0;
            }
            $v['item'] = $info;
        }

        $list['data']['user'] = $user;
        $list['data']['item'] = $item;

        return table_assign(0, '', $list);
    }

    /**
     * 查看固定资产工时
     */
    public function getEquHours(){

        $param = get_params();
        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        $year = $param['year'];
        $month = $param['month'];

        $where = [
            'ewh.eid' => $eid,
            'ewh.year' => $year,
            'ewh.month' => $month,
            'ewh.status' => 0,
        ];

        //获取固定资产
        $user = Db::name('EquipmentWorkHours')->alias('ewh')
            ->where($where)
            ->group('ewh.eq_id')
            ->field('ewh.eq_id as id,e.name')
            ->join('Equipment e' , 'e.id = ewh.eq_id')
            ->select()->toArray();

        //获取项目
        $item = Db::name('EquipmentWorkHours')->alias('ewh')
            ->where($where)
            ->group('ewh.item_id')
            ->field('ewh.item_id as id,i.name')
            ->join('item i' , 'i.id = ewh.item_id')
            ->select()->toArray();

        $detail = $this->_getHours($eid , $year , $month);

        View::assign('user', $user);
        View::assign('item', $item);
        View::assign('eid', $eid);
        View::assign('detail', $detail);
        View::assign('year', $year);
        View::assign('month', $month);
        return view();
    }


    /**
     * 删除工时
     */
    public function delete(){

        $param = get_params();
        $eid =$param['eid'];
        $year =$param['year'];
        $month =$param['month'];

        $count = Db::name('EquipmentWorkHours')->where(['eid' => $eid ,'year' => $year , 'month' => $month])->count();

        $res = true;
        if($count > 0){
            $res = Db::name('EquipmentWorkHours')->where(['eid' => $eid ,'year' => $year , 'month' => $month])->delete();
        }

        if ($res !== false) {
            add_log('delete', '', $param);
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "删除失败");
        }

    }

    /**
     * 获取固定资产工时公共方法
     * @param $eid
     * @param $year
     * @param $month
     * @return array

     */
    public function _getHours($eid,$year,$month){

        $where = [
            'eid' => $eid,
            'year' => $year,
            'month' => $month,
            'status' => 0,
        ];

        $work_user = Db::name('EquipmentWorkHours')->where($where)->select()->toArray();

        $list = [];
        if(!empty($work_user)){
            foreach ($work_user as $k =>$v){

                $list[$v['eq_id'].'-'.$v['item_id']] = $v;

            }
        }

        return $list;
    }

}
